package com.lich.controller;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import com.github.pagehelper.PageInfo;
import com.lich.entity.Product;
import com.lich.entity.Users;
import com.lich.entity.vo.Result;
import com.lich.service.ProductService;
import com.lich.service.UsersService;
import com.lich.util.JsonUtils;

/**
 * @description 用户控制器
 * @date 2016年8月29日
 * @author lich-thinkpad
 */
@Controller
@RequestMapping("/user")
public class UsersController {
	private static Logger logger = LoggerFactory.getLogger(UsersController.class);
	@Resource
	UsersService usersService;
	@Resource
	ProductService productService;

	/**
	 * @description 获取访问方ip
	 * @date 2016年8月30日
	 * @author lich-thinkpad
	 * @param request
	 * @return
	 * @throws Exception
	 */
	public String getIpAddr(HttpServletRequest request) throws Exception {
		String ip = request.getHeader("X-Real-IP");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			return ip;
		}
		ip = request.getHeader("X-Forwarded-For");
		if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个IP值，第一个为真实IP。
			int index = ip.indexOf(',');
			if (index != -1) {
				return ip.substring(0, index);
			} else {
				return ip;
			}
		} else {
			return request.getRemoteAddr();
		}
	}

	/**
	 * @description 登陆
	 * @date 2016年8月29日
	 * @author lich-thinkpad
	 * @param redirectAttributes
	 * @param username
	 * @param password
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(RedirectAttributes redirectAttributes, String username, String password) {
		try {
			SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password));
			return "redirect:/manager/main";
		} catch (AuthenticationException e) {
			Result<Object> result = new Result<>();
			result.setSuccess(false);
			result.setMessage("用户名或密码错误");
			redirectAttributes.addFlashAttribute("result", result);
			return "redirect:/login";
		}
	}

	/**
	 * @description 注册
	 * @date 2016年8月31日
	 * @author lich-thinkpad
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public ModelAndView register(HttpServletRequest request, Users user) {
		Result<Users> result = new Result<>();
		user.setCreated(new Date());
		user.setModified(new Date());
		Users oldUser = usersService.getByUsername(user.getUsername());
		if (oldUser != null) {
			result.setObject(user);
			result.setSuccess(false);
			result.setMessage("用户名已被使用");
			logger.warn("用户名已被使用,入参" + JsonUtils.object2Json(user));
			return new ModelAndView("login", "result", result);
		}
		// FIXME 暂时默认注册用户为admin
		if (StringUtils.isBlank(user.getRole())) {
			user.setRole(Users.ADMIN);
		}
		// 获取访问方ip
		try {
			user.setLastIp(getIpAddr(request));
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("获取访问方ip失败");
			logger.error("获取访问方ip失败");
			return new ModelAndView("login", "result", result);
		}
		// 向数据库添加信息
		if (usersService.add(user, null) > 0) {
			result.setSuccess(true);
			result.setMessage("注册成功");
		} else {
			result.setSuccess(false);
			result.setMessage("注册失败");
			logger.error("注册失败");
		}
		return new ModelAndView("login", "result", result);
	}

	/**
	 * @description 添加用户
	 * @date 2016年9月7日
	 * @author lich
	 * @param request
	 * @param user
	 * @param productIds
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public ModelAndView add(HttpServletRequest request, Users user, Integer[] productIds) {
		Result<Users> result = new Result<>();
		user.setCreated(new Date());
		user.setModified(new Date());
		Users oldUser = usersService.getByUsername(user.getUsername());
		if (oldUser != null) {
			result.setObject(user);
			result.setSuccess(false);
			result.setMessage("用户名已被使用");
			logger.warn("用户名已被使用,入参" + JsonUtils.object2Json(user));
			return new ModelAndView(new MappingJackson2JsonView(), "result", result);
		}
		// 获取访问方ip
		try {
			user.setLastIp(getIpAddr(request));
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("获取访问方ip失败");
			logger.error("获取访问方ip失败");
			return new ModelAndView("login", "result", result);
		}
		// 向数据库添加信息
		if (usersService.add(user, productIds) > 0) {
			result.setSuccess(true);
			result.setMessage("添加成功");
		} else {
			result.setSuccess(false);
			result.setMessage("添加失败,入参" + JsonUtils.object2Json(user));
			logger.error("添加失败");
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ModelAndView update(HttpServletRequest request, Users user, Integer[] productIds) {
		Result<Users> result = new Result<>();
		user.setModified(new Date());
		// 向数据库添加信息
		if (usersService.update(user, productIds) > 0) {
			result.setSuccess(true);
			result.setMessage("更新成功");
		} else {
			result.setSuccess(false);
			result.setMessage("更新失败,入参" + JsonUtils.object2Json(user));
			logger.error("更新失败");
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	/**
	 * @description 删除用户
	 * @date 2016年9月8日
	 * @author lich
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	public ModelAndView delete(int userId) {
		Result<Users> result = new Result<>();
		if (usersService.deleteById(userId) > 0) {
			result.setSuccess(true);
			result.setMessage("删除用户成功");
		} else {
			result.setSuccess(false);
			result.setMessage("删除用户失败");
			logger.error("删除用户失败，入参userId=" + userId);
		}
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}

	/**
	 * @description 登出
	 * @date 2016年8月31日
	 * @author lich-thinkpad
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(RedirectAttributes redirectAttributes) {
		// 使用权限管理工具进行用户的退出，跳出登录，给出提示信息
		SecurityUtils.getSubject().logout();
		redirectAttributes.addFlashAttribute("message", "您已安全退出");
		return "redirect:/login";
	}

	/**
	 * @description 用户添加页面
	 * @date 2016年9月7日
	 * @author lich
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView addPage() {
		Result<List<Product>> result = new Result<>();
		List<Product> products = productService.getAll();
		result.setObject(products);
		result.setSuccess(true);
		result.setMessage("查询所有产品成功");
		return new ModelAndView("manager/user/add", "result", result);
	}

	/**
	 * @description 用户列表页面
	 * @date 2016年9月7日
	 * @author lich
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView listPage(Integer pageNum) {
		Result<PageInfo<Users>> result = new Result<>();
		if(pageNum == null || pageNum<1){
			pageNum = 1;
		}
		PageInfo<Users> pageInfo = usersService.getPage(pageNum);
		result.setObject(pageInfo);
		result.setSuccess(true);
		result.setMessage("查询所有产品成功");
		return new ModelAndView("manager/user/list", "result", result);
	}

	/**
	 * @description 用户的产品
	 * @date 2016年9月12日
	 * @author lich
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/product", method = RequestMethod.GET)
	public ModelAndView userProduct(int userId) {
		Result<Object> result = new Result<>();
		List<Product> products = productService.getByUserId(userId);
		result.setObject(products);
		result.setSuccess(true);
		result.setMessage("查询用户的产品成功");
		return new ModelAndView(new MappingJackson2JsonView(), "result", result);
	}
}
